<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('图片标注')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox">
                    <div class="ibox-title">
                        <h5>图片标注</h5>
                    </div>
                    <div class="ibox-content">
                        <div class="row">
                            <!-- 左侧图片展示区域 -->
                            <div class="col-sm-6" style="border-right: 2px solid #e0e0e0; padding-right: 30px;">
                                <div class="form-group">
                                    <label class="control-label">图片展示：</label>
                                    <div class="m-b-sm text-center" id="pictureContainer" style="min-height: 450px; display: flex; align-items: center; justify-content: center; flex-direction: column; position: relative;">
                                        <!-- 倒计时显示 -->
                                        <div id="countdownDisplay" class="alert alert-info" style="margin-bottom: 15px; display: none;">
                                            <i class="fa fa-clock-o"></i> 剩余时间：<span id="countdownTime" style="font-weight: bold;">04:00</span>
                                        </div>
                                        <img id="currentPicture" src="" alt="待标注图片" class="img-responsive" style="max-width: 100%; max-height: 400px; display: none; cursor: pointer;" onclick="showImageModal()" title="点击查看大图">
                                        <div id="loadingMessage" class="loading-container">
                                            <div class="loading-spinner">
                                                <div class="spinner-ring"></div>
                                                <div class="spinner-ring"></div>
                                                <div class="spinner-ring"></div>
                                                <div class="spinner-ring"></div>
                                            </div>
                                            <div class="loading-text">正在加载图片...</div>
                                        </div>
                                        <div id="noPictureMessage" class="alert alert-warning" style="display: none;">
                                            <i class="fa fa-info-circle"></i> 图片已经标注完成
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 右侧标注区域 -->
                            <div class="col-sm-6" style="padding-left: 30px;">
                                <form id="annotationForm" class="form-horizontal">
                                    <input type="hidden" id="pictureId" name="id">
                                    
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">左脚诊断：</label>
                                        <div class="col-sm-8">
                                            <select name="leftFoot" id="leftFoot" class="form-control" required>
                                                <option value="">请选择</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">右脚诊断：</label>
                                        <div class="col-sm-8">
                                            <select name="rightFoot" id="rightFoot" class="form-control" required>
                                                <option value="">请选择</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">腿型分类：</label>
                                        <div class="col-sm-8">
                                            <select name="leg" id="leg" class="form-control" required>
                                                <option value="">请选择</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <div class="col-sm-offset-3 col-sm-8">
                                            <button id="submitBtn" type="button" class="btn btn-primary" onclick="submitAnnotation()">
                                        <i class="fa fa-save"></i> 提交标注
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="showAnnotationHistory()">
                                        <i class="fa fa-history"></i> 标注历史
                                    </button>
                                        </div>
                                    </div>
                                    
                                    <!-- 倒计时说明 -->
                                    <div class="form-group">
                                        <div class="col-sm-offset-3 col-sm-8">
                                            <div class="alert alert-info" style="margin-bottom: 0; padding: 10px 15px; font-size: 13px; background-color: #e3f2fd; border-color: #2196f3; color: #1976d2;">
                                                <i class="fa fa-info-circle"></i> 
                                                <strong>倒计时提示：</strong>每张图片标注时间限制为4分钟，超时将自动切换到下一张图片。请及时完成标注并提交。
                                                <br><small style="color: #64b5f6;">💡 提示：图片加载完成后倒计时开始，提交后会重置计时器。</small>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 图片预览弹窗 -->
    <div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" style="width: 90%; max-width: 1200px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="imageModalLabel">图片预览</h4>
                </div>
                <div class="modal-body text-center" style="padding: 20px; background-color: #f5f5f5; overflow: hidden;">
                    <div style="position: relative; min-height: 70vh; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                        <img id="modalImage" src="" alt="预览图片" style="max-width: 100%; max-height: 60vh; cursor: grab; transition: transform 0.3s ease; position: relative; z-index: 1;">
                    </div>
                    <div style="margin-top: 15px; position: relative; z-index: 2;">
                        <button type="button" class="btn btn-default" onclick="zoomImage(1.2)">
                            <i class="fa fa-search-plus"></i> 放大
                        </button>
                        <button type="button" class="btn btn-default" onclick="zoomImage(0.8)">
                            <i class="fa fa-search-minus"></i> 缩小
                        </button>
                        <button type="button" class="btn btn-default" onclick="resetZoom()">
                            <i class="fa fa-refresh"></i> 重置
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    
    <!-- Loading动画样式 -->
    <style>
        .loading-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            min-width: 200px;
            min-height: 150px;
        }
        
        .loading-spinner {
            position: relative;
            width: 60px;
            height: 60px;
            margin-bottom: 20px;
        }
        
        .spinner-ring {
            position: absolute;
            width: 100%;
            height: 100%;
            border: 3px solid transparent;
            border-radius: 50%;
            animation: spin 1.5s linear infinite;
        }
        
        .spinner-ring:nth-child(1) {
            border-top-color: #3498db;
            animation-duration: 1.2s;
        }
        
        .spinner-ring:nth-child(2) {
            border-right-color: #e74c3c;
            animation-duration: 1.4s;
            animation-delay: 0.2s;
        }
        
        .spinner-ring:nth-child(3) {
            border-bottom-color: #f39c12;
            animation-duration: 1.6s;
            animation-delay: 0.4s;
        }
        
        .spinner-ring:nth-child(4) {
            border-left-color: #2ecc71;
            animation-duration: 1.8s;
            animation-delay: 0.6s;
        }
        
        @keyframes spin {
            0% {
                transform: rotate(0deg) scale(1);
                opacity: 1;
            }
            50% {
                transform: rotate(180deg) scale(1.1);
                opacity: 0.8;
            }
            100% {
                transform: rotate(360deg) scale(1);
                opacity: 1;
            }
        }
        
        .loading-text {
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            text-align: center;
            animation: pulse 2s ease-in-out infinite;
            margin-top: 10px;
        }
        
        @keyframes pulse {
            0%, 100% {
                opacity: 0.7;
                transform: translateY(0);
            }
            50% {
                opacity: 1;
                transform: translateY(-2px);
            }
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .loading-container {
                min-width: 150px;
                min-height: 120px;
                padding: 30px 15px;
            }
            
            .loading-spinner {
                width: 45px;
                height: 45px;
                margin-bottom: 15px;
            }
            
            .loading-text {
                font-size: 14px;
            }
        }
        
        /* 深色主题适配 */
        @media (prefers-color-scheme: dark) {
            .loading-container {
                background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
                border: 1px solid rgba(255, 255, 255, 0.1);
            }
            
            .loading-text {
                color: #ecf0f1;
            }
        }
    </style>
    
    <script th:inline="javascript">
  
        var currentZoom = 1; // 当前缩放比例
        var countdownInterval = null; // 倒计时定时器
        var countdownSeconds = 240; // 倒计时总秒数（4分钟）
        
        $(function() {
            // 页面加载时初始化
            loadDictionaryData();
            loadNextPicture();
            
            // 绑定弹窗关闭事件，清理滚轮事件
            $("#imageModal").on("hidden.bs.modal", function() {
                $("#modalImage").off("wheel.zoom wheel.drag");
                resetZoom();
            });
        });
        
        /**
         * 显示图片预览弹窗
         */
        function showImageModal() {
            var imgSrc = $("#currentPicture").attr("src");
            if (imgSrc) {
                $("#modalImage").attr("src", imgSrc);
                $("#imageModal").modal('show');
                resetZoom();
                
                // 绑定滚轮事件
                setTimeout(function() {
                    $("#modalImage").off("wheel.zoom").on("wheel.zoom", function(e) {
                        e.preventDefault();
                        var delta = e.originalEvent.deltaY;
                        if (delta > 0) {
                            zoomImage(0.9); // 向下滚动，缩小
                        } else {
                            zoomImage(1.1); // 向上滚动，放大
                        }
                    });
                }, 300);
            }
        }
        
        /**
         * 缩放图片
         */
        function zoomImage(factor) {
            currentZoom *= factor;
            currentZoom = Math.max(0.1, Math.min(currentZoom, 3)); // 限制缩放范围在10%到300%之间
            $("#modalImage").css("transform", "scale(" + currentZoom + ")");
            
            // 如果缩放比例过大，调整图片位置避免遮挡按钮
            if (currentZoom > 1.5) {
                $("#modalImage").css("margin-bottom", "120px"); // 调整为120px，适配更大的弹窗
                // 启用拖动功能
                enableDrag();
            } else {
                $("#modalImage").css("margin-bottom", "0");
                // 禁用拖动功能并重置位置
                disableDrag();
            }
        }
        
        /**
         * 重置缩放
         */
        function resetZoom() {
            currentZoom = 1;
            $("#modalImage").css("transform", "scale(1)");
            $("#modalImage").css("margin-bottom", "0");
            $("#modalImage").css({"left": "0", "top": "0"});
            disableDrag();
            
            // 重新绑定滚轮事件（如果存在的话）
            setTimeout(function() {
                $("#modalImage").off("wheel.zoom").on("wheel.zoom", function(e) {
                    e.preventDefault();
                    var delta = e.originalEvent.deltaY;
                    if (delta > 0) {
                        zoomImage(0.9);
                    } else {
                        zoomImage(1.1);
                    }
                });
            }, 100);
        }
        
        /**
         * 显示标注历史弹窗
         */
        function showAnnotationHistory() {
            var index = layer.open({
                type: 2,
                title: '标注历史',
                shadeClose: true,
                shade: 0.8,
                area: ['85%', '85%'],
                content: ctx + 'system/picture/annotateHistoryPage',
                success: function(layero, index) {
                    // 弹窗加载成功后的回调 - 移除全屏逻辑，保持原有尺寸
                    // layer.full(index); // 注释掉这行，避免自动全屏
                }
            });
        }
        
        /**
         * 重新标注图片（供子页面调用）
         */
        function reannotatePicture(pictureData) {
            if (pictureData) {
                // 设置当前图片数据
                $("#pictureId").val(pictureData.id);
                
                // 设置标注数据
                $("#rightFoot").val(pictureData.rightFoot);
                $("#leftFoot").val(pictureData.leftFoot);
                $("#leg").val(pictureData.leg);
                
                // 隐藏加载和提示信息
                $("#loadingMessage").hide();
                $("#noPictureMessage").hide();
                
                // 启用提交按钮
                $("#submitBtn").prop("disabled", false);
                
                // 设置图片源并等待加载完成
                $("#currentPicture").attr("src", pictureData.url);
                
                // 先隐藏图片，显示loading状态
                $("#currentPicture").hide();
                $("#loadingMessage").show();
                
                // 监听图片加载完成事件
                $("#currentPicture").off('load.countdown').on('load.countdown', function() {
                    // 图片加载完成后隐藏loading，显示图片并启动倒计时
                    $("#loadingMessage").hide();
                    $(this).show();
                    startCountdown();
                });
                
                // 如果图片已经缓存，load事件可能不会触发，需要手动检查
                if ($("#currentPicture")[0].complete && $("#currentPicture").attr('src')) {
                    $("#loadingMessage").hide();
                    $("#currentPicture").show();
                    startCountdown();
                }
            }
        }
        
        /**
         * 启动倒计时
         */
        function startCountdown() {
            // 清除之前的倒计时
            clearInterval(countdownInterval);
            
            // 重置倒计时秒数
            countdownSeconds = 240;
            
            // 显示倒计时元素
            $("#countdownDisplay").show();
            
            // 更新显示
            updateCountdownDisplay();
            
            // 启动倒计时
            countdownInterval = setInterval(function() {
                countdownSeconds--;
                updateCountdownDisplay();
                
                // 倒计时结束，自动加载下一张图片
                if (countdownSeconds <= 0) {
                    clearInterval(countdownInterval);
                    loadNextPicture();
                }
            }, 1000);
        }
        
        /**
         * 更新倒计时显示
         */
        function updateCountdownDisplay() {
            var minutes = Math.floor(countdownSeconds / 60);
            var seconds = countdownSeconds % 60;
            var timeString = minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
            
            $("#countdownTime").text(timeString);
            
            // 根据剩余时间设置颜色
            var $countdownDisplay = $("#countdownDisplay");
            if (countdownSeconds > 60) {
                $countdownDisplay.removeClass('alert-warning alert-danger').addClass('alert-info');
            } else if (countdownSeconds > 30) {
                $countdownDisplay.removeClass('alert-info alert-danger').addClass('alert-warning');
            } else {
                $countdownDisplay.removeClass('alert-info alert-warning').addClass('alert-danger');
            }
        }
        
        /**
         * 停止倒计时
         */
        function stopCountdown() {
            clearInterval(countdownInterval);
            $("#countdownDisplay").hide();
        }
        
        /**
         * 启用拖动功能
         */
        function enableDrag() {
            var $img = $("#modalImage");
            var $container = $img.parent();
            var isDragging = false;
            var startX, startY, initialX = 0, initialY = 0;
            
            // 设置图片为相对定位，便于拖动
            $img.css({"position": "relative", "left": "0", "top": "0"});
            $img.css("cursor", "move");
            
            $img.off("mousedown.drag").on("mousedown.drag", function(e) {
                isDragging = true;
                startX = e.clientX;
                startY = e.clientY;
                initialX = parseInt($img.css("left")) || 0;
                initialY = parseInt($img.css("top")) || 0;
                e.preventDefault();
            });
            
            $(document).off("mousemove.drag").on("mousemove.drag", function(e) {
                if (!isDragging) return;
                
                var deltaX = e.clientX - startX;
                var deltaY = e.clientY - startY;
                
                var newLeft = initialX + deltaX;
                var newTop = initialY + deltaY;
                
                // 限制拖动范围，防止拖出容器
                var containerWidth = $container.width();
                var containerHeight = $container.height();
                var imgWidth = $img.width() * currentZoom;
                var imgHeight = $img.height() * currentZoom;
                
                var maxLeft = Math.max(0, (imgWidth - containerWidth) / 2);
                var maxTop = Math.max(0, (imgHeight - containerHeight) / 2);
                var minLeft = -maxLeft;
                var minTop = -maxTop;
                
                newLeft = Math.max(minLeft, Math.min(maxLeft, newLeft));
                newTop = Math.max(minTop, Math.min(maxTop, newTop));
                
                $img.css({"left": newLeft + "px", "top": newTop + "px"});
            });
            
            $(document).off("mouseup.drag").on("mouseup.drag", function() {
                isDragging = false;
            });
            
            // 禁用滚轮默认行为，避免与拖动冲突
            $img.off("wheel.drag").on("wheel.drag", function(e) {
                e.preventDefault();
            });
        }
        
        /**
         * 禁用拖动功能
         */
        function disableDrag() {
            var $img = $("#modalImage");
            $img.off("mousedown.drag wheel.drag");
            $(document).off("mousemove.drag mouseup.drag");
            $img.css("cursor", "grab");
        };
        
        /**
         * 加载数据字典
         */
        function loadDictionaryData() {
            // 加载右腿诊断选项
            $.ajax({
                url: ctx + "system/dict/data/list",
                type: "POST",
                data: { dictType: "foot_type" },
                success: function(result) {
                    if (result.code == 0) {
                        var options = '';
                        $.each(result.rows, function(index, item) {
                            if (item.dictValue == 0) {
                                options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
                        $("#rightFoot").html(options);
                        $("#leftFoot").html(options);
                    }
                }
            });
            
            // 加载腿型分类选项
            $.ajax({
                url: ctx + "system/dict/data/list",
                type: "POST",
                data: { dictType: "leg_type" },
                success: function(result) {
                    if (result.code == 0) {
                        var options = '';
                        $.each(result.rows, function(index, item) {
                            if (item.dictValue == 0) {
                                options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
                        $("#leg").html(options);
                    }
                }
            });
        }
        
        /**
         * 加载下一张图片
         */
        function loadNextPicture() {
            $("#loadingMessage").show();
            $("#currentPicture").hide();
            $("#noPictureMessage").hide();
            
            // 重置缩放状态
            resetZoom();
            
            // 停止之前的倒计时
            stopCountdown();
            
            $.ajax({
                url: ctx + "system/picture/getNext",
                type: "GET",
                success: function(result) {
                    
                    if (result.code == 0) {
                        // 成功获取图片
                        var picture = result.data;
                        $("#pictureId").val(picture.id);
                        
                        // 重置表单
                        $("#annotationForm")[0].reset();
                        
                        // 启用提交按钮
                        $("#submitBtn").prop("disabled", false);
                        
                        // 设置图片源并等待加载完成
                        $("#currentPicture").attr("src", picture.url);
                        
                        // 先确保图片是隐藏状态
                        $("#currentPicture").hide();
                        
                        // 监听图片加载完成事件
                        $("#currentPicture").off('load.countdown').on('load.countdown', function() {
                            // 图片加载完成后隐藏loading，显示图片并启动倒计时
                            $("#loadingMessage").hide();
                            $(this).show();
                            startCountdown();
                        });
                        
                        // 如果图片已经缓存，load事件可能不会触发，需要手动检查
                        if ($("#currentPicture")[0].complete && $("#currentPicture").attr('src')) {
                            $("#loadingMessage").hide();
                            $("#currentPicture").show();
                            startCountdown();
                        }
                    } else {
                        // 没有更多图片
                        $("#loadingMessage").hide();
                        $("#noPictureMessage").text(result.msg).show();
                        $("#pictureId").val("");
                        // 禁用提交按钮
                        $("#submitBtn").attr("disabled", "true");
                    }
                },
                error: function() {
                    $("#loadingMessage").hide();
                    $.modal.alertError("加载图片失败");
                }
            });
        }
        
        /**
         * 提交标注信息
         */
        function submitAnnotation() {
            // 表单验证
            var pictureId = $("#pictureId").val();
            var rightFoot = $("#rightFoot").val();
            var leftFoot = $("#leftFoot").val();
            var leg = $("#leg").val();
            
            if (!pictureId) {
                $.modal.alertWarning("没有可标注的图片");
                return;
            }
            
            if (rightFoot == 0) {
                $.modal.alertWarning("请选择右脚诊断");
                return;
            }
            
            if (leftFoot == 0) {
                $.modal.alertWarning("请选择左脚诊断");
                return;
            }
            
            if (leg == 0) {
                $.modal.alertWarning("请选择腿型分类");
                return;
            }
            
            // 提交数据
            $.ajax({
                url: ctx + "system/picture/save",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                    id: pictureId,
                    rightFoot: rightFoot,
                    leftFoot: leftFoot,
                    leg: leg
                }),
                success: function(result) {
                    if (result.code == 0) {
                        // 停止倒计时
                        stopCountdown();
                        
                        var data = result.data;
                        if (data.completed) {
                            // 标注完成
                            $.modal.alertSuccess(data.message, function() {
                            });
                            $("#currentPicture").hide();
                            $("#submitBtn").attr("disabled", "true");
                            $("#noPictureMessage").text(data.message).show();
                        } else {
                            // 继续下一张
                            $.modal.msgSuccess("标注保存成功");
                            // 加载下一张图片
                            if (data.nextPicture) {
                                $("#pictureId").val(data.nextPicture.id);
                                $("#currentPicture").attr("src", data.nextPicture.url);
                                $("#annotationForm")[0].reset();
                                
                                // 先隐藏图片，显示loading状态
                                $("#currentPicture").hide();
                                $("#loadingMessage").show();
                                
                                // 监听图片加载完成事件
                                $("#currentPicture").off('load.countdown').on('load.countdown', function() {
                                    // 图片加载完成后隐藏loading，显示图片并启动倒计时
                                    $("#loadingMessage").hide();
                                    $(this).show();
                                    startCountdown();
                                });
                                
                                // 如果图片已经缓存，load事件可能不会触发，需要手动检查
                                if ($("#currentPicture")[0].complete) {
                                    $("#loadingMessage").hide();
                                    $("#currentPicture").show();
                                    startCountdown();
                                }
                            } else {
                                loadNextPicture();
                            }
                        }
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("保存标注信息失败");
                }
            });
        }
    </script>
</body>
</html>